package liangtWorkSpace.mage;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName LengthOfLongestSubstring
 * @Description : 给定一个字符串，请你找出其中不含有重复字符的 最长子串 的长度。
 * @Author : LiangT
 * @Date : 2020/6/19 17:05
 */
public class LengthOfLongestSubstring {
    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() <1){
            return 0;
        }
        String zi = s.substring(0,0);
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length;i++){
            StringBuffer stringBuffer = new StringBuffer();
            for (int j = i;j < chars.length;j++){
                if (stringBuffer.toString().indexOf(String.valueOf(chars[j])) >=0){
                    break;
                }
                stringBuffer.append(chars[j]);
            }
            if (stringBuffer.toString().length() > zi.length()){
                zi = stringBuffer.toString();
            }
        }
        return zi.length();
    }


    public static int lengthOfLongestSubstring1(String s) throws InterruptedException {
        // 哈希集合，记录每个字符是否出现过
        Set<Character> occ = new HashSet<Character>();
        int n = s.length();
        // 右指针，初始值为 -1，相当于我们在字符串的左边界的左侧，还没有开始移动
        int rk = -1, ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i != 0) {
                // 左指针向右移动一格，移除一个字符
                occ.remove(s.charAt(i - 1));
            }
            while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                // 不断地移动右指针
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            // 第 i 到 rk 个字符是一个极长的无重复字符子串
            ans = Math.max(ans, rk - i + 1);
        }
        return ans;
    }

    public int lengthOfLongestSubstring2(String s) {
        int[] last = new int[128];
        for (int i = 0; i < 128;i++){
            last[i] = -1;
        }
        int n = s.length();

        int res = 0;
        int start = 0;
        for(int i = 0; i < n; i++){
            int index = s.charAt(i);
            start = Math.max(start,last[index]+1);
            res = Math.max(res,i-start+1);
            last[index] = i;
        }
        return res;
    }
    public static void main(String[] args) throws InterruptedException {
        List a = new ArrayList();
        String ste = "asdfghjklfguzxcvbnsgnx";
        System.out.println(ste.charAt(12));
        System.out.println(lengthOfLongestSubstring1("asdfghjklfguzxcvbnsgnx"));
    }
}
